package com.kf.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kf.config.AliyunOSSUtil;
import com.kf.config.RedisUtil;
import com.kf.mapper.*;
import com.kf.pojo.*;
import com.kf.pojo.form.*;
import com.kf.pojo.iterator.StudentAggregateImpl;
import com.kf.service.*;
import com.kf.util.MD5Utils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用户服务impl
 *
 * @author Honey
 * @date 2022/12/23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService {
    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper userRoleMapper;

    @Resource
    UserRoleService userRoleService;
    @Resource
    TeacherMapper teacherMapper;

    @Resource
    AdminMapper adminMapper;

    @Resource
    StudentMapper studentMapper;
    @Resource
    CategoryMapper categoryMapper;
    @Resource
    ChoCgyMapper choCgyMapper;
    @Resource
    ChoCgyRecordMapper choCgyRecordMapper;
    @Resource
    GradeMapper gradeMapper;
    @Resource
    PaperFileMapper paperFileMapper;
    @Resource
    RecordsMapper recordsMapper;
    @Resource
    ReportMapper reportMapper;
    @Resource
    WenFileMapper wenFileMapper;
    @Resource
    StudentService studentService;
    @Resource
    AdminService adminService;
    @Resource
    TeacherService teacherService;
    @Resource
    AliyunOSSUtil  aliyunOSSUtil;

    @Resource
    RedisUtil redisUtil;


    @Override
    public User queryUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(AddUserForm adduserForm) {
        User user = new User();
        User user1 = queryUserByName(adduserForm.getUsername());

        user.setUsername(adduserForm.getUsername());
        String encrypt = MD5Utils.encrypt(adduserForm.getUsername(), adduserForm.getPassword());
        user.setPassword(encrypt);
        user.setState(adduserForm.getState());
        user.setName(adduserForm.getName());
        user.setEmail(adduserForm.getEmail());
        user.setSex(adduserForm.getSex());
        user.setPhone(adduserForm.getPhone());
        user.setDepartment(adduserForm.getDepartment());
        user.setStatus(1);
        userMapper.insert(user);
    }


    @Resource
    protected SqlSessionFactory sqlSessionFactory;
    public int addUserSpace(List<User> userList) {
        //开启批处理
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false );
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        for (User user : userList) {
//            UserSpaceEntity userSpaceEntity = userSpaceConverter.to(user);
            mapper.insert(user);
        }
        //进行批次提交
        sqlSession.commit();
        //清除缓存
        sqlSession.clearCache();
        //关闭连接
        sqlSession.close();

        return 0;
    }
    @Override
    public void updatePassword(User user){
        userMapper.updateById(user);
    }

    @Override
    public List<User> selectAllUser() {

        return userMapper.selectList(null);
    }

    @Override
    public IPage<User> pageUser(String name,int current,int size) {
        Page<User> users = new Page<>(current, size);
        users.setDesc("user_id");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name).or().like("username",name);
        queryWrapper.eq("deleted",0);
        return userMapper.selectPage(users, queryWrapper);
    }

    @Override
    public void deleteUser(List<Integer> userId) {
        userMapper.deleteBatchIds(userId);
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ChoCgyRecord> choCgyRecordQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        QueryWrapper<PaperFile> paperFileQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Records> recordsQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Report> reportQueryWrapper = new QueryWrapper<>();
        QueryWrapper<WenFile> wenFileQueryWrapper = new QueryWrapper<>();
        for (Integer integer : userId) {
            userRoleQueryWrapper.eq("user_id",integer);
            userRoleMapper.delete(userRoleQueryWrapper);
            studentQueryWrapper.eq("user_id",integer);
            studentMapper.delete(studentQueryWrapper);
            teacherQueryWrapper.eq("user_id",integer);
            teacherMapper.delete(teacherQueryWrapper);
            adminQueryWrapper.eq("user_id",integer);
            adminMapper.delete(adminQueryWrapper);
            categoryQueryWrapper.eq("user_id",integer);
            categoryMapper.delete(categoryQueryWrapper);
            choCgyQueryWrapper.eq("user_id",integer);
            choCgyMapper.delete(choCgyQueryWrapper);
            choCgyRecordQueryWrapper.eq("user_id",integer);
            choCgyRecordMapper.delete(choCgyRecordQueryWrapper);
            gradeQueryWrapper.eq("user_id",integer);
            gradeMapper.delete(gradeQueryWrapper);
            paperFileQueryWrapper.eq("user_id",integer);
            PaperFile paperFile = paperFileMapper.selectOne(paperFileQueryWrapper);
            if(paperFile!=null){
                aliyunOSSUtil.deleteFile(paperFile.getPath() + "/" + paperFile.getFilename() + "." + paperFile.getSuffix());
            }
            paperFileMapper.delete(paperFileQueryWrapper);
            recordsQueryWrapper.eq("user_id",integer);
            recordsMapper.delete(recordsQueryWrapper);
            reportQueryWrapper.eq("user_id",integer);
            reportMapper.delete(reportQueryWrapper);
            wenFileQueryWrapper.eq("user_id",integer);
            WenFile wenFile = wenFileMapper.selectOne(wenFileQueryWrapper);
            if(wenFile!=null){
                aliyunOSSUtil.deleteFile(wenFile.getPath() + "/" + wenFile.getFilename() + "." + wenFile.getSuffix());
            }
            wenFileMapper.delete(wenFileQueryWrapper);


        }

    }

    @Override
    public List<User> selectUserByName(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        return userMapper.selectUserByName(name);
    }

    @Override
    public List<User> selectUserListById(List<Integer> userId) {
        List<User> list=new ArrayList<>();
        for (Integer integer : userId) {
            User user = userMapper.selectById(integer);
            list.add(user);
        }
        return list;

    }

    @Override
    public int countTeaByDepartmen(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department",user.getDepartment());
        queryWrapper.eq("state",2);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public int countStuByDepartmen(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department",user.getDepartment());
        queryWrapper.eq("state",1);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public User findByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void addUserAll(AddUserForm adduserForm, User user1) {
        if (adduserForm.getState()==1){
            StudentAggregateImpl studentAggregate = new StudentAggregateImpl();
            Student student = (Student)FactoryObject.createPeople("student");
            student.setUserId(user1.getUserId());
            student.setStuName(adduserForm.getName());
            student.setStuMail(adduserForm.getEmail());
            student.setStuSex(adduserForm.getSex());
            student.setStuPhone(adduserForm.getPhone());
            student.setStuDepartment(adduserForm.getDepartment());
            student.setStuStatus(1);
            studentService.insert(student);
            UserRole userRole = new UserRole();
            userRole.setUserId(user1.getUserId());
            userRole.setRoleId(1);
            userRoleService.insert(userRole);
        }else if(adduserForm.getState()==2) {
            Teacher teacher = (Teacher)FactoryObject.createPeople("teacher");

            teacher.setUserId(user1.getUserId());
            teacher.setTeaDepartment(adduserForm.getDepartment());
            teacher.setTeaEmail(adduserForm.getEmail());
            teacher.setTeaPhone(adduserForm.getPhone());
            teacher.setTeaSex(adduserForm.getSex());
            teacher.setTeaName(adduserForm.getName());
            teacher.setTeaStatus(1);
            teacherService.insert(teacher);
            UserRole userRole = new UserRole();
            userRole.setUserId(user1.getUserId());
            userRole.setRoleId(2);
            userRoleService.insert(userRole);
        }else{
            Admin admin = new Admin();
            admin.setUserId(user1.getUserId());
            admin.setAdEmail(adduserForm.getEmail());
            admin.setAdPhone(adduserForm.getPhone());
            admin.setAdName(adduserForm.getName());
            admin.setAdSex(adduserForm.getSex());
            admin.setAdStatus(1);
            adminService.insert(admin);
            UserRole userRole = new UserRole();
            userRole.setUserId(user1.getUserId());
            userRole.setRoleId(3);
            userRoleService.insert(userRole);
        }
    }

    @Override
    public StudentForm getStudent(Student student,User user,int state) {
        StudentForm studentForm = new StudentForm();
        studentForm.setState(state);
        studentForm.setStuClass(student.getStuClass());
        studentForm.setStuSex(student.getStuSex());
        studentForm.setStuMail(student.getStuMail());
        studentForm.setStuDepartment(student.getStuDepartment());
        studentForm.setStuName(student.getStuName());
        studentForm.setStuPhone(student.getStuPhone());
        studentForm.setStuWx(student.getStuWx());
        studentForm.setStuQq(student.getStuQq());
        studentForm.setStuTitle(student.getStuTitle());
        studentForm.setStuProfessional(student.getStuProfessional());
        studentForm.setUsername(user.getUsername());
        studentForm.setStatus(user.getStatus());
        studentForm.setUserId(user.getUserId());
        return studentForm;
    }

    @Override
    public TeacherForm getTeacher(Teacher teacher, User user, int state) {
        TeacherForm teacherForm = new TeacherForm();
        teacherForm.setState(state);
        teacherForm.setUsername(user.getUsername());
        teacherForm.setStatus(teacher.getTeaStatus());
        teacherForm.setTeaDepartment(user.getDepartment());
        teacherForm.setTeaEmail(user.getEmail());
        teacherForm.setTeaPhone(user.getPhone());
        teacherForm.setTeaRecord(teacher.getTeaRecord());
        teacherForm.setTeaName(teacher.getTeaName());
        teacherForm.setTeaPost(teacher.getTeaPost());
        teacherForm.setTeaWx(teacher.getTeaWx());
        teacherForm.setTeaSex(teacher.getTeaSex());
        teacherForm.setUserId(teacher.getUserId());
        return teacherForm;
    }

    @Override
    public AdminForm getTeacher(Admin admin, User user, int state) {
        return null;
    }

    @Override
    public PageFormUser reidsGetUser(SelectForm selectForm,String pagekeys) throws Exception {
        ReentrantLock reentrantLock = new ReentrantLock();
        PageFormUser pageFormUser = new PageFormUser();
        if(reentrantLock.tryLock()){
            IPage<User> userIPage =pageUser(selectForm.getName(), selectForm.getCurrent(), selectForm.getSize());
            List<User> records = userIPage.getRecords();
            pageFormUser.setList(records);
            pageFormUser.setTotal(userIPage.getTotal());
            redisUtil.set(pagekeys,pageFormUser);
            reentrantLock.unlock();
            return pageFormUser;
        }else {
            Thread.sleep(100);
            return reidsGetUser(selectForm, pagekeys);
        }
    }
}
